/**
 * 根据坐标信息从原图中切割出指定区域
 * @param {string} imageUrl - 原图URL
 * @param {Array} questions - 题目信息数组
 * @returns {Promise<Array>} 切割后的图片数组
 */
export const createImageCrops = async (imageUrl, questions) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";

    img.onload = () => {
      try {
        const croppedImages = [];

        for (let i = 0; i < questions.length; i++) {
          const question = questions[i];
          const result = {
            id: question.id,
            text: question.text,
          };

          // 切割题干区域
          if (question.bbox) {
            const questionCanvas = cropImageArea(img, question.bbox);
            result.questionImage = questionCanvas.toDataURL("image/png");
          }

          // 切割作答区域
          if (question.answerArea) {
            const answerCanvas = cropImageArea(img, question.answerArea);
            result.answerImage = answerCanvas.toDataURL("image/png");
          }

          croppedImages.push(result);
        }

        resolve(croppedImages);
      } catch (error) {
        reject(error);
      }
    };

    img.onerror = () => {
      reject(new Error("图片加载失败"));
    };

    img.src = imageUrl;
  });
};

/**
 * 切割图片指定区域
 * @param {HTMLImageElement} img - 原图
 * @param {Object} bbox - 边界框坐标
 * @returns {HTMLCanvasElement} 切割后的canvas
 */
const cropImageArea = (img, bbox) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  // 确保坐标在图片范围内
  const x = Math.max(0, Math.min(bbox.x, img.width));
  const y = Math.max(0, Math.min(bbox.y, img.height));
  const width = Math.max(1, Math.min(bbox.width, img.width - x));
  const height = Math.max(1, Math.min(bbox.height, img.height - y));

  canvas.width = width;
  canvas.height = height;

  // 绘制切割区域
  ctx.drawImage(
    img,
    x,
    y,
    width,
    height, // 源区域
    0,
    0,
    width,
    height // 目标区域
  );

  return canvas;
};

/**
 * 使用Canvas API调整图片大小
 * @param {HTMLCanvasElement} canvas - 原canvas
 * @param {number} maxWidth - 最大宽度
 * @param {number} maxHeight - 最大高度
 * @returns {HTMLCanvasElement} 调整后的canvas
 */
export const resizeCanvas = (canvas, maxWidth = 800, maxHeight = 600) => {
  const { width, height } = canvas;

  // 计算缩放比例
  const scaleX = maxWidth / width;
  const scaleY = maxHeight / height;
  const scale = Math.min(scaleX, scaleY, 1); // 不放大，只缩小

  if (scale >= 1) {
    return canvas; // 不需要调整
  }

  const newWidth = Math.floor(width * scale);
  const newHeight = Math.floor(height * scale);

  const newCanvas = document.createElement("canvas");
  const ctx = newCanvas.getContext("2d");

  newCanvas.width = newWidth;
  newCanvas.height = newHeight;

  // 使用高质量缩放
  ctx.imageSmoothingEnabled = true;
  ctx.imageSmoothingQuality = "high";

  ctx.drawImage(canvas, 0, 0, newWidth, newHeight);

  return newCanvas;
};

/**
 * 为切割区域添加边框和标注
 * @param {string} imageUrl - 原图URL
 * @param {Array} questions - 题目信息数组
 * @returns {Promise<string>} 标注后的图片URL
 */
export const addAnnotationsToImage = async (imageUrl, questions) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";

    img.onload = () => {
      try {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        canvas.width = img.width;
        canvas.height = img.height;

        // 绘制原图
        ctx.drawImage(img, 0, 0);

        // 添加标注
        questions.forEach((question, index) => {
          // 题干区域标注
          if (question.bbox) {
            drawBoundingBox(ctx, question.bbox, `题目${index + 1}`, "#ff4d4f");
          }

          // 作答区域标注
          if (question.answerArea) {
            drawBoundingBox(
              ctx,
              question.answerArea,
              `作答${index + 1}`,
              "#52c41a"
            );
          }
        });

        resolve(canvas.toDataURL("image/png"));
      } catch (error) {
        reject(error);
      }
    };

    img.onerror = () => {
      reject(new Error("图片加载失败"));
    };

    img.src = imageUrl;
  });
};

/**
 * 绘制边界框
 * @param {CanvasRenderingContext2D} ctx - Canvas上下文
 * @param {Object} bbox - 边界框坐标
 * @param {string} label - 标签文字
 * @param {string} color - 颜色
 */
const drawBoundingBox = (ctx, bbox, label, color) => {
  ctx.strokeStyle = color;
  ctx.lineWidth = 2;
  ctx.setLineDash([5, 5]);

  // 绘制矩形边框
  ctx.strokeRect(bbox.x, bbox.y, bbox.width, bbox.height);

  // 绘制标签背景
  ctx.fillStyle = color;
  const labelWidth = ctx.measureText(label).width + 10;
  const labelHeight = 20;

  ctx.fillRect(bbox.x, bbox.y - labelHeight, labelWidth, labelHeight);

  // 绘制标签文字
  ctx.fillStyle = "#fff";
  ctx.font = "12px Arial";
  ctx.textAlign = "left";
  ctx.textBaseline = "middle";
  ctx.fillText(label, bbox.x + 5, bbox.y - labelHeight / 2);

  // 重置样式
  ctx.setLineDash([]);
};

/**
 * 检测图片中的空白区域（可能的作答区域）
 * @param {HTMLImageElement} img - 图片元素
 * @param {Object} searchArea - 搜索区域
 * @returns {Array} 检测到的空白区域
 */
export const detectBlankAreas = async (img, searchArea) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  canvas.width = searchArea.width;
  canvas.height = searchArea.height;

  // 绘制搜索区域
  ctx.drawImage(
    img,
    searchArea.x,
    searchArea.y,
    searchArea.width,
    searchArea.height,
    0,
    0,
    searchArea.width,
    searchArea.height
  );

  // 获取图像数据
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const data = imageData.data;

  // 简单的空白检测：寻找大面积的白色或浅色区域
  const blankAreas = [];
  const threshold = 240; // 像素亮度阈值
  const minAreaSize = 100; // 最小区域面积

  // 这里可以实现更复杂的空白区域检测算法
  // 目前返回一个默认的空白区域
  if (searchArea.height > minAreaSize) {
    blankAreas.push({
      x: searchArea.x,
      y: searchArea.y + searchArea.height * 0.3,
      width: searchArea.width,
      height: searchArea.height * 0.7,
    });
  }

  return blankAreas;
};
